import { BeforeInsert, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { Exclude } from 'class-transformer';
import * as bcrypt from 'bcryptjs';

@Entity('user')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ length: 50 }) // 用户名称
  username: string;

  @Column({ length: 50, default: null }) // 用户昵称
  nickname: string;

  @Exclude()
  @Column({ select: false })
  password: string; // 密码

  @Column({ default: null })
  avatar: string; // 头像

  @Column({ default: null })
  email: string; // 邮箱

  @Column({ default: null })
  openid: string; // openid

  @Column('simple-enum', { enum: ['root', 'vip', 'member'], default: 'member' })
  role: string; // 用户角色

  @Column({
    name: 'create_time',
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP',
  })
  createTime: Date;

  @Column({
    name: 'update_time',
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP',
  })
  updateTime: Date;

  @BeforeInsert()
  async encryptPwd() {
    if (!this.password) return;
    this.password = await bcrypt.hashSync(this.password, 10);
  }
}
